import express, { Router } from "express";
import errorMiddleware from "./middleware/error.mw";
import Controller from "./interface/controller.if";
import cookieParser from "cookie-parser";

/**
 * 这是包装好的服务器应用。
 */
export default class App {
  public app: express.Application;
  public port: number;
  /**
   *
   * 向App传入要使用的控制器和要监听的端口
   */
  constructor(controllers: Controller[], port: number = 5000) {
    this.app = express();
    this.port = port;

    this.useMiddleware();
    this.useController(controllers);
    this.useErrorHandler();
    this.listen();
  }
  private useErrorHandler() {
    this.app.use(errorMiddleware);
  }
  /**
   *
   * 初始化使用自义定的控制器
   */
  private useController = (controllers: Controller[]) => {
    controllers.forEach((con) => {
      this.app.use("/", con.router);
    });
  };
  /**\
   * 初始化使用常规中间件 比如 body-parser之类的
   */
  private useMiddleware = () => {
    this.app.use(express.json());
    this.app.use(cookieParser());
  };
  /**
   *
   * 初始化,令express监听 this.port 端口
   */
  public listen = () => {
    const port = this.port;
    this.app.listen(port);
    console.log(`服务在${port}端口等候,`);
  };
}
